package com.chengyu.core.service.common.impl;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.chengyu.core.exception.CommonException;
import com.chengyu.core.service.common.QrCodeService;
import com.chengyu.core.util.RestTemplateUtil;
import com.chengyu.core.utils.CommonUtil;
import com.chengyu.core.utils.QRCodeUtil;
import com.chengyu.core.vo.QrCodeVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private WxMaService customWxMaService;

    /**
     * 二维码
     *
     * @return QrCodeVo
     */
    @Override
    public QrCodeVo getWecahtQrCode(JSONObject data) throws WxErrorException {
        if (data == null || CollUtil.isEmpty(data.keySet())) {
            throw new CommonException("生成微信参数不能为空");
        }
        String page = data.getString("page");
        String scene = data.getString("scene");
        QrCodeVo vo = new QrCodeVo();
        // 获取小程序二维码生成实例
        WxMaQrcodeService wxMaQrcodeService = customWxMaService.getQrcodeService();
        WxMaCodeLineColor codeLineColor = new WxMaCodeLineColor("0", "0", "0");
        byte[] wxaCodeUnlimitBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(scene, page, 300, false, codeLineColor, true);
        String base64Image = CommonUtil.getBase64Image(Base64.encodeBase64String(wxaCodeUnlimitBytes));
        vo.setCode(base64Image);
        return vo;
    }

    /**
     * 远程图片转base64
     *
     * @param url 图片链接地址
     * @return QrCodeVo
     */
    @Override
    public QrCodeVo urlToBase64(String url) {
        byte[] bytes = restTemplateUtil.getBuffer(url);
        String base64Image = CommonUtil.getBase64Image(Base64.encodeBase64String(bytes));
        QrCodeVo vo = new QrCodeVo();
        vo.setCode(base64Image);
        return vo;
    }

    /**
     * 字符串转base64
     *
     * @param text 待转换字符串
     * @return QrCodeVo base64格式
     */
    @Override
    public QrCodeVo strToBase64(String text, Integer width, Integer height) {
        if ((width < 50 || height < 50) && (width > 500 || height > 500) && text.length() >= 999) {
            throw new CommonException("生成二维码参数不合法");
        }
        String base64Image;
        try {
            base64Image = QRCodeUtil.crateQRCode(text, width, height);
        } catch (Exception e) {
            throw new CommonException("生成二维码异常");
        }
        QrCodeVo vo = new QrCodeVo();
        vo.setCode(base64Image);
        return vo;
    }
}

